﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace SingleSystem
{
    public partial class Form1 : Form
    {
        private UIBarOption optionB3 = new UIBarOption();
        private UIBarOption optionR = new UIBarOption();
        private UIBarSeries seriesB3;
        private UIBarSeries seriesR;
        private int timerVal = 1;
        private System.Windows.Forms.Timer timer2 = new System.Windows.Forms.Timer();
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            uiBarChart1.SetOption(new UIBarOption());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 1000;
            timer.Tick += new EventHandler(timer1_Tick);
            timer.Start();
            //初始化获取串口下拉框数据
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            if (ports.Length > 0)
            {
                foreach (String portNmae in ports)
                {
                    com.Items.Add(portNmae);
                }
            }
            com.Text = ports[0];//串口默认值


            /****************非常重要***************/
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
        }

        private void com_button_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                    com_button.Text = "打开串口";
                    label18.Text = "串口已关闭";
                }
                else
                {

                    serialPort1.PortName = com.Text;
                    serialPort1.BaudRate = Convert.ToInt32(com_rate.Text);//十进制数据转换
                    serialPort1.Open();
                    label18.Text = "串口已打开";
                    com_button.Text = "关闭串口";
                    /*if (ubloxkg.Active) {
                        serialPort1.WriteLine("SETUBLOX 1$");
                    }
                    if (zssjkg.Active){
                        serialPort1.WriteLine("$SETREVIVE 1$");
                    }*/
                    //serialPort1.WriteLine("$GETSTAT$");
                }


            }
            catch
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                }
                MessageBox.Show("串口打开失败,请检查串口", "错误");
            }
        }

        private List<byte> buffer = new List<byte>(10240);
        private void port_DataReceived(object render, SerialDataReceivedEventArgs e)//串口数据接收事件
        {
            try {
                if (!serialPort1.IsOpen) { 
                    return;
                }
                buffer.Clear();

                //16进制发送数据还原
                int i_InNum;//输入缓冲区中字节数
                i_InNum = serialPort1.BytesToRead;
                byte[] ReceivedData = new byte[i_InNum];//创建接收字节数组
                serialPort1.Read(ReceivedData, 0, i_InNum);//读取接收的数据
                string str = String.Empty;
                for (int i = 0; i < ReceivedData.Length; i++)
                {
                    str += Convert.ToString(ReceivedData[i], 16).ToUpper().Length == 1 ? "0" + Convert.ToString(ReceivedData[i], 16).ToUpper() : Convert.ToString(ReceivedData[i], 16).ToUpper();//转换为大写的16进制字符串
                }
                //writeFile(DateTime.Now.ToString("位置1 yyyy-MM-dd HH:mm:ssfff") + ":" + str);
                while (!str.EndsWith("0D0A")) {
                    Thread.Sleep(50);
                    int length;//输入缓冲区中字节数
                    length = serialPort1.BytesToRead;
                    byte[] temp = new byte[length];//创建接收字节数组
                    serialPort1.Read(temp, 0, length);//读取接收的数据
                    for (int i = 0; i < temp.Length; i++)
                    {
                        str += Convert.ToString(temp[i], 16).ToUpper().Length == 1 ? "0" + Convert.ToString(temp[i], 16).ToUpper() : Convert.ToString(temp[i], 16).ToUpper();//转换为大写的16进制字符串
                    }
                }
                
                //writeFile(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ssfff") + ":"+str);
                if (!String.IsNullOrEmpty(str) && str.StartsWith("5354")) {
                      handle_data(str); 
                }
            }
            catch (Exception ex) { }


        }

        public void handle_data(string content) {
            switch (content.Substring(4,2)) {
                case "01":
                    //日期
                    string year = Convert.ToInt32(content.Substring(6, 4), 16) + "-";
                    string month = Convert.ToInt32(content.Substring(10, 2), 16) + "-";
                    string day = Convert.ToInt32(content.Substring(12, 2), 16) + "";
                    date.Text = year+month + day;
                    //时间
                    string hour = (Convert.ToInt32(content.Substring(14, 2), 16)>=10 ? Convert.ToInt32(content.Substring(14, 2), 16)+"" : "0"+ Convert.ToInt32(content.Substring(14, 2), 16)) + ":";
                    string minute = (Convert.ToInt32(content.Substring(16, 2), 16)>=10? Convert.ToInt32(content.Substring(16, 2), 16)+"":"0"+ Convert.ToInt32(content.Substring(16, 2), 16)) + ":";
                    string second = Convert.ToInt32(content.Substring(18, 2), 16)>=10 ? Convert.ToInt32(content.Substring(18, 2), 16) + "" : "0"+Convert.ToInt32(content.Substring(18, 2), 16);
                    time.Text = hour+minute+second;
                    if (!writeFlag)
                    {
                        //模块状态
                        string stateStr = content.Substring(22, 2);
                        switch (stateStr)
                        {
                            case "00":
                                dt.Checked = true;
                                break;
                            case "01":
                                mnq1.Checked = true;
                                break;
                        }
                        //B3
                        b3.Value = Convert.ToInt32(content.Substring(24, 2), 16);
                        //S
                        s.Value = Convert.ToInt32(content.Substring(26, 2), 16);
                        //模拟器1
                        s1.Value = Convert.ToInt32(content.Substring(28, 2), 16);
                        s2.Value = Convert.ToInt32(content.Substring(30, 2), 16);
                    }
                    //经度
                    latitude_Hemi.Text = Convert.ToString(DataUtil.HexToString(content.Substring(32, 2)));
                    latitude.Text = (Convert.ToDouble(Convert.ToInt64(content.Substring(34, 10), 16)) / 10000000) + "";
                    //纬度
                    longitude_Hemi.Text = Convert.ToString(DataUtil.HexToString(content.Substring(44, 2)));
                    longitude.Text = (Convert.ToDouble(Convert.ToInt64(content.Substring(46, 10), 16)) / 10000000) + "";
                    //高度
                    hight.Text = (Convert.ToDouble(Convert.ToInt32(content.Substring(56, 4), 16)) / 10) + "";
                    //状态
                    state.Text = Convert.ToInt32(content.Substring(60, 2), 16)==0 ? "不定位":"已定位";
                    //检波器1
                    if (content.Substring(62, 4).Equals("4646"))
                    {
                        lgl1.Text = "FF";
                    }
                    else if (content.Substring(62, 4).Equals("4545")) {
                        lgl1.Text = "EE";
                    }
                    else
                    {
                        lgl1.Text = (Convert.ToDecimal(DataUtil.HexStringToNegative(content.Substring(62, 4)) != 0 ? DataUtil.HexStringToNegative(content.Substring(62, 4)) : Convert.ToInt32(content.Substring(62, 4),16)) / 10) + "";

                    }
                    if (content.Substring(66, 4).Equals("4646"))
                    {
                        lgl2.Text = "FF";
                    }
                    else if (content.Substring(66, 4).Equals("4545")) {
                        lgl2.Text = "EE";
                    }
                    else
                    {
                        lgl2.Text = (Convert.ToDecimal(DataUtil.HexStringToNegative(content.Substring(66, 4)) != 0 ? DataUtil.HexStringToNegative(content.Substring(66, 4)) : Convert.ToInt32(content.Substring(66, 4),16)) / 10) + "";
                    }
                    break;
                case "02":
                    //处理图
                    handle_zssj(content);
                    break;
                case "03":
                    //处理图
                    handle_zssj(content);
                    break;
            }
        }
        private void handle_zssj(string str)
        {
            try
            {
                
                handle_chart(str);
                
            }
            catch (Exception e) {
                throw e;
           }
        }
        private void handle_chart(String str) {
            string flag = str.Substring(4, 2);
            byte[] strArr = DataUtil.HexStrToToHexByte(str); 
            if (strArr.Length % 2 == 0 && strArr.Length < 5) {
                return;
            }
            switch (flag)
            {
                case "02":
                    optionB3 = new UIBarOption();
                    optionB3.Title.Text = "星况信息";
                    //设置图例
                    optionB3.Legend = new Sunny.UI.UILegend();
                    // 图例水平布局
                    optionB3.Legend.Orient = UIOrient.Horizontal;
                    // 图例放置在左上角
                    optionB3.Legend.Top = UITopAlignment.Top;
                    optionB3.Legend.Left = UILeftAlignment.Left;
                    // 两个图例分别是Bar1和Bar2
                    optionB3.Legend.AddData("B3", Color.Green);
                    // 设置系列
                    seriesB3 = new UIBarSeries();
                    // 第一系列Bar1
                    seriesB3.Name = "B3";
                    for (int i = 4; i < strArr.Length-2; i = i + 2)
                    {
                        if ((i + 1) < strArr.Length-2)
                        {
                            optionB3.XAxis.Data.Add(Convert.ToInt32(DataUtil.ByteToHex(new byte[] { strArr[i] }), 16) + "");
                            seriesB3.AddData(Convert.ToDouble(Convert.ToInt32(DataUtil.ByteToHex(new byte[] { strArr[i + 1] }), 16)), Color.Green);
                        }

                    }

                    // 设置横坐标内容
                    // 第一系列和第二系列的元素交织分布
                    // 所以Mon是指第一和二系列的第一个元素的横坐标
                    // Tue指第一和二系列的第二个元素的横坐标
                    optionB3.Series.Add(seriesB3);
                    if (radioB3.Checked)
                    {
                        uiBarChart1.SetOption(optionB3);
                    }
                    break;
                case "03":
                    optionR = new UIBarOption();
                    optionR.Title.Text = "RDSS信息";
                    //设置图例
                    optionR.Legend = new Sunny.UI.UILegend();
                    // 图例水平布局
                    optionR.Legend.Orient = UIOrient.Horizontal;
                    // 图例放置在左上角
                    optionR.Legend.Top = UITopAlignment.Top;
                    optionR.Legend.Left = UILeftAlignment.Left;
                    // 两个图例分别是Bar1和Bar2
                    optionR.Legend.AddData("RDSS");
                    // 设置系列
                    seriesR = new UIBarSeries();
                    // 第一系列Bar1
                    seriesR.Name = "RDSS";
                    int a=1;
                    for (int i = 3; i < strArr.Length-2; i = i+1)
                    {
                       
                        optionR.XAxis.Data.Add(a++ +"");
                        seriesR.AddData(Convert.ToDouble(Convert.ToInt32(DataUtil.ByteToHex(new byte[] { strArr[i] }), 16)));
                        

                    }

                    // 设置横坐标内容
                    // 第一系列和第二系列的元素交织分布
                    // 所以Mon是指第一和二系列的第一个元素的横坐标
                    // Tue指第一和二系列的第二个元素的横坐标
                    optionR.Series.Add(seriesR);
                    if (radioR.Checked)
                    {
                        uiBarChart1.SetOption(optionR);
                    }
                    break;

            }
            
            
        }
       
        private void timer1_Tick(object sender, EventArgs e)
        {
            label19.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            //writeFile(DateTime.Now.ToString("运行日志 yyyy-MM-dd HH:mm:ssfff") + ":" + "运行串口开关"+serialPort1.IsOpen);
        }

        private void timer2_Tick(object sender, EventArgs e) {
            //MessageBox.Show("停止");
            writeFlag = false;
            timer2.Stop();
        }


        private void writeFile(String dataStr) {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(@"C:\dataTest.txt",true);//创建StreamWriter对象
                                                 //量程配置
                
                sw.WriteLine(dataStr);

            }
            catch (Exception ex)
            {
                //MessageBox.Show("写入流异常：" + ex.ToString());
                return;
            }
            finally
            {
                try { 
                    if(null != sw) {
                        sw.Close();
                    }
                   
                } catch {

                }
               
            }
        }

        private void set2_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    //发送数据
                    //对天
                    byte[] func= new byte[1];
                    if (dt.Checked) {
                        new byte[] { 0x00 }.CopyTo(func,0);
                    }
                    if (mnq1.Checked) {
                        new byte[] { 0x01 }.CopyTo(func, 0);
                    }
                   
                    //设置B3 
                    byte[] b3Value = new byte[] {DataUtil.IntToHexByte(Convert.ToInt32(b3.Value))[1]};
                    //设置对天s
                    byte[] dtValue = new byte[] {DataUtil.IntToHexByte(Convert.ToInt32(s.Value))[1]};
                    //设置模拟器s
                    byte[] s1Value = new byte[] {DataUtil.IntToHexByte(Convert.ToInt32(s1.Value))[1]};
                    //设置模拟器s2
                    byte[] s2Value = new byte[] {DataUtil.IntToHexByte(Convert.ToInt32(s2.Value))[1]};
                   
                    

                    byte[] data = new byte[func.Length+b3Value.Length + dtValue.Length + s1Value.Length + s2Value.Length];
                    func.CopyTo(data, 0);
                    b3Value.CopyTo(data, func.Length);
                    dtValue.CopyTo(data, func.Length+b3Value.Length);
                    s1Value.CopyTo(data, func.Length+b3Value.Length+ dtValue.Length);
                    s2Value.CopyTo(data, func.Length+b3Value.Length + dtValue.Length + s1Value.Length);
                    DataUtil.sendData(serialPort1, DataUtil.packageData(data));
                    
                }
                writeFlag = false;
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void dt_CheckedChanged(object sender, EventArgs e)
        {
            if (dt.Checked) {
                mnq1.Checked = false;
            }
        }

        private void mnq1_CheckedChanged(object sender, EventArgs e)
        {
            if (mnq1.Checked) {
                dt.Checked = false;
            }
        }
       
        private bool writeFlag = false;
        private void b3_Enter(object sender, EventArgs e)
        {
            writeFlag = true;
            timer2.Interval = timerVal * 60 * 1000;
            timer2.Tick += new EventHandler(timer2_Tick);
        }

        private void s_Enter(object sender, EventArgs e)
        {
            writeFlag = true;
            timer2.Interval = timerVal * 60 * 1000;
            timer2.Tick += new EventHandler(timer2_Tick);
            timer2.Start();
        }

        private void s1_Enter(object sender, EventArgs e)
        {
            writeFlag = true;
            timer2.Interval = timerVal * 60 * 1000;
            timer2.Tick += new EventHandler(timer2_Tick);
            timer2.Start();
        }

        private void s2_Enter(object sender, EventArgs e)
        {
            //MessageBox.Show("停止");
            writeFlag = true;
            timer2.Interval = timerVal * 60 * 1000;
            timer2.Tick += new EventHandler(timer2_Tick);
            timer2.Start();
        }

        private void radioB3_CheckedChanged(object sender, EventArgs e)
        {
            if (radioB3.Checked) {
                uiBarChart1.SetOption(optionB3);
            }
        }

        private void radioR_CheckedChanged(object sender, EventArgs e)
        {
            if (radioR.Checked) {
                uiBarChart1.SetOption(optionR);
            }
        }

        private void mnq1_MouseClick(object sender, MouseEventArgs e)
        {
            writeFlag = true;
        }

        private void dt_MouseClick(object sender, MouseEventArgs e)
        {
            writeFlag = true;
        }

        private void mnq2_MouseClick(object sender, MouseEventArgs e)
        {
            writeFlag = true;
        }

        

        /**
private void lgl1_Enter(object sender, EventArgs e)
{
   writeFlag = true;
   timer2.Interval = timerVal * 60 * 1000;
   timer2.Tick += new EventHandler(timer2_Tick);
   timer2.Start();
}

private void lgl2_Enter(object sender, EventArgs e)
{
   writeFlag = true;
   timer2.Interval = timerVal * 60 * 1000;
   timer2.Tick += new EventHandler(timer2_Tick);
   timer2.Start();
}**/
    }
}
